package com.project.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dtyunxi.vo.AccessToken;
import com.dtyunxi.vo.Authorization;
import com.dtyunxi.vo.JsapiTicket;
import com.project.common.Constants;

public class WeiXinUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(WeiXinUtil.class);
	
	public static String getOpenid(String appId, String secret, String code){
		Authorization authorization = com.dtyunxi.util.WeiXinUtil.getAuthorization(appId, secret, code);
		String openId="";
		if(authorization!=null){
			openId =  authorization.getOpenid();
		}
		return openId;
	}
	
	public static synchronized AccessToken getAccessToken(String appId, String secret){
		//从缓存获取AccessToken
		AccessToken accessToken = (AccessToken) EhcacheUtil.get(Constants.WEIXIN_CACHE, "accessToken"+appId);
		logger.info("从缓存获取AccessToken:{}",accessToken);
		if(accessToken==null){//已过期
			//重新获取token
			accessToken= com.dtyunxi.util.WeiXinUtil.getAccessToken(appId, secret);
			logger.info("重新获取AccessToken:{}",accessToken.getAccessToken());
			EhcacheUtil.put(Constants.WEIXIN_CACHE, "accessToken"+appId, accessToken);
		}
		return accessToken;
	}
	
	public static synchronized JsapiTicket getJsapiTicket(String appId, String secret){
		//从缓存获取jsapiTicket
		JsapiTicket jsapiTicket = (JsapiTicket) EhcacheUtil.get(Constants.WEIXIN_CACHE, "ticket"+appId);
		if(jsapiTicket==null){//已过期
			//重新获取jsapiTicket
			AccessToken accessToken = getAccessToken(appId, secret);
			jsapiTicket = com.dtyunxi.util.WeiXinUtil.getJsapiTicket(accessToken.getAccessToken());
			if(jsapiTicket!=null){						
				EhcacheUtil.put(Constants.WEIXIN_CACHE, "ticket"+appId, jsapiTicket);
			}
		}
		return jsapiTicket;
	}

}
